package com.maimang.platform.controller.monitor;

import com.maimang.platform.annotation.Log;
import com.maimang.platform.base.BaseController;
import com.maimang.platform.base.Result;
import com.maimang.platform.common.entity.SysUserOnline;
import com.maimang.platform.enums.BusinessType;
import com.maimang.platform.enums.OnlineStatus;
import com.maimang.platform.page.TableDataInfo;
import com.maimang.platform.common.service.SysUserOnlineService;
import com.maimang.platform.shiro.session.OnlineSession;
import com.maimang.platform.shiro.session.SessionDao;
import com.maimang.platform.common.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Rocky
 * @version 1.0.0
 * @类名 SysUserOnlineController
 * @描述 <br>在线用户监控</br>
 * @日期 2019-04-25 16:33
 * @email jintaozhao@qq.com
 */
@Controller
@RequestMapping("/monitor/online")
public class SysUserOnlineController extends BaseController {

	private String prefix = "monitor/online";

	@Autowired
	private SysUserOnlineService userOnlineService;

	@Autowired
	private SessionDao sessionDao;

	@RequiresPermissions("monitor:online:view")
	@GetMapping
	public String online() {
		return prefix + "/online";
	}

	@RequiresPermissions("monitor:online:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(SysUserOnline userOnline) {
		startPage();
		List<SysUserOnline> list = userOnlineService.selectUserOnlineList(userOnline);
		return getDataTable(list);
	}

	@RequiresPermissions("monitor:online:batchForceLogout")
	@Log(title = "批量在线用户强退", businessType = BusinessType.FORCE)
	@PostMapping("/batchForceLogout")
	@ResponseBody
	public Result batchForceLogout(@RequestParam("ids[]") String[] ids) {
		for (String sessionId : ids) {
			userLogout(sessionId);
		}
		return success();
	}

	@RequiresPermissions("monitor:online:forceLogout")
	@Log(title = "在线用户强退", businessType = BusinessType.FORCE)
	@PostMapping("/forceLogout")
	@ResponseBody
	public Result forceLogout(String sessionId) {
		return userLogout(sessionId);
	}

	private Result userLogout(String sessionId) {
		SysUserOnline online = userOnlineService.selectOnlineById(sessionId);
		if (sessionId.equals(ShiroUtils.getSessionId())) {
			return error("当前登录用户" + online.getLoginName() + "无法强退");
		}
		if (online == null) {
			return error("用户" + online.getLoginName() + "已下线");
		}
		OnlineSession onlineSession = (OnlineSession) sessionDao.readSession(online.getSessionId());
		if (onlineSession == null) {
			return error("用户" + online.getLoginName() + "已下线");
		}
		onlineSession.setStatus(OnlineStatus.off_line);
		online.setStatus(OnlineStatus.off_line);
		userOnlineService.saveOnline(online);
		return success();
	}
}